import { Jqdetail } from 'jqdetail_model.js';
var util = require('../../utils/common.js'); //引入公共JS
var wxParse = require('../../wxParse/wxParse.js'); //引入
var WSCoordinate = require('../../utils/WSCoordinate.js'); //引入坐标系转换

var jqdetail = new Jqdetail();
var fsm = tt.getFileSystemManager();
var FILE_BASE_NAME = 'tmp_base64src';
var Small_program_code2 = '';
const app = getApp(); //引入自定义头部导航

Page({
  data: {
    showIcon: true,
    //显示返回键以及首页
    datas: [],
    fxFlag: true,
    //分享
    _menu: 0,
    //默认显示订票
    _list: 0,
    //默认显示订票的信息
    maskHidden: false,
    wx_name: '',
    //微信名称
    wx_image: '',
    //微信头像
    getUserInfo: false,
    mtype: '',
    stockFlag: true,
    //缺货登记
    selectData: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
    //下拉列表的数据
    index: 0,
    //选择的下拉列表下标
    mMid: '',
    z: '',
    kefuphoneArr: []
  },
  //页面打开计算购票须知和演出详情内容的高度，高度超过则隐藏部分内容
  onLoad: function (options) {

    // 显示分享展示按钮
    tt.showShareMenu({
      success(res) {
        console.log("已成功显示转发按钮");
      },
      fail(err) {
        console.log("showShareMenu 调用失败", err.errMsg);
      },
      complete(res) {
        console.log("showShareMenu 调用完成");
      },
    });
    
    console.log('景区',options)
    var scene = options.scene;
    if (scene) {
      var arr = scene.split("%2C");

      if (arr.length == 2) {
        scene = arr[0];
        console.log(scene);
        console.log(arr);
        this.data.mMid = arr[1];
      } else {
        scene = arr[0];
      }
      tt.setStorageSync('mMid', this.data.mMid);
    } else {
      tt.setStorageSync('mMid', '');
    } 
    //判断公众号来源
    var source = options.source;

    if (source) {
      tt.setStorageSync('source', source);
    } else {//wx.setStorageSync('source', '');
    }

    if (options.id == 89317) {
      var etc = 1;
      this.setData({
        etc: etc
      });
    } else {
      var etc = 0;
      this.setData({
        etc: etc
      });
    }

    var z = options.z;
    if (z) {
      this.setData({
        z: z
      });
    }else{
      this.setData({
        z:'DY'
      })
    }

    if (scene) {
      id = scene;
    } else {
      var id = options.id; //项目id
    }

    this.data.id = id;

    this._onLoad(); 
    
    // 获取客服手机号
    let kefuphone = tt.getStorageSync('kefuphoneArr');
    if (!kefuphone) {
      util.kefuphone();
    }
    this.setData({
      kefuphoneArr: kefuphone.slice(0, 2)
    });
  },
  
  _onLoad: function () {
    if (!this.data.id) {
      tt.navigateBack({
        delta: 2
      });
    } else {
      jqdetail.JqdetailFor(this.data.id, res => {
        console.log(res.shorttitle + '的id是' + res.aid,res); //勿删
        wxParse.wxParse('article', 'html', res.body, this, 5);
        if (res.beizhu != null) {
          wxParse.wxParse('beizhu', 'html', res.beizhu, this, 5);
        }
        this.data.litpic = res.litpic;
        this.setData({
          'Jqdetail': res
        });
      });
      jqdetail.getAnswers(this.data.id, res => {
        this.setData({
          'Answers': res,
          'length': res.length
        });
      }); //订票须知循环展示有pricestyle

      jqdetail.getJQdetail(this.data.id, res => {
        if (res) {
          var that = this;
          var listData = res;
          var newinfo = [];
          var pricestyle = [];
          var pricestyle2 = [];
          var pricestyle3 = [];

          for (let i = 0; i < listData.length; i++) {
            if (listData[i].paixu != '') {
              listData.sort(this.compare('paixu', true));
            }
          }
          for (let i = 0; i < listData.length; i++) {
            pricestyle.push(listData[i].pricestyle);
          } //数组去重
          for (var i in pricestyle) {
            // 遍历原数组
            var isadd = true; //设置标记
            for (var j in pricestyle2) {
              //遍历新数组
              if (pricestyle[i] === pricestyle2[j]) {
                //如果当前原数组中的项，在新数组中存在，则标记为‘不添加’，并跳出新数组遍历
                isadd = false;
                break;
              }
            }
            if (isadd) {
              pricestyle2.push(pricestyle[i]); //若标记为‘添加’（即遍历新数组后，没有发现相同项），则添加进新数组
            }
          } //遍历新数组，存储类型

          for (var i in pricestyle2) {
            pricestyle3.push(pricestyle2[i]);
          } //订票须知

          for (let i = 0; i < listData.length; i++) {
            newinfo.push(listData[i].xlongName);
            listData[i]['toggle'] = true; //添加toggle 属性

            listData[i]['_id'] = i;
          } //订票须知HTML转换WXML

          for (let j = 0; j < newinfo.length; j++) {
            if (res[j]['pricesLess'] != 0) {
              res[j]['xyhprice'] = Number(res[j]['xyhprice']) + Number(res[j]['pricesLess']);
            }
            wxParse.wxParse('xlongName' + j, 'html', newinfo[j], that);
            if (j === newinfo.length - 1) {
              var infolist = wxParse.wxParseTemArray('infolist', 'xlongName', newinfo.length, that);
            }
          }

          this.setData({
            'Commodity': res,
            datas: listData,
            pricestyle: pricestyle3
          });
        } else {
          console.log(159);
          this.setData({
            datas: 1
          });
        }
      }); //订票须知循环展示没有pricestyle

      jqdetail.getJQdetail2(this.data.id, res => {
        //console.log(res)
        var that = this;
        var listData2 = res;
        var newinfo = [];

        for (let i = 0; i < listData2.length; i++) {
          newinfo.push(listData2[i].xlongName);
          listData2[i]['toggle'] = true; //添加toggle 属性
          listData2[i]['_id'] = i;
        }
        for (let j = 0; j < newinfo.length; j++) {
          wxParse.wxParse('xlongName' + j, 'html', newinfo[j], that);
          if (j === newinfo.length - 1) {
            var infolist = wxParse.wxParseTemArray('infolist', 'xlongName', newinfo.length, that);
          }
        }
        if (listData2 == '') {
          var listData2 = '1';
        }
        this.setData({
          'Commodity': res,
          datas2: listData2
        });
      });
      jqdetail.getJQListArr(this.data.id, res => {
        this.setData({
          'getJQListArr': res
        });
      });
      jqdetail.getJQListArr2(this.data.id, res => {
        this.setData({
          'getJQListArr2': res
        });
      });
    }
  },
  compare: function (property, bol) {
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];

      if (bol) {
        return value1 - value2;
      } else {
        return value2 - value1;
      }
    };
  },
  //打开缺货登记
  want_book: function (e) {
    this.data.aid = e.currentTarget.dataset.aid;
    this.data.priceid = e.currentTarget.dataset.id;
    this.setData({
      stockFlag: false
    });
  },
  // 关闭缺货登记
  stockHide: function (e) {
    this.setData({
      stockFlag: true
    });
  },
  // 点击下拉显示框
  selectTap: function (e) {
    this.setData({
      show: !this.data.show
    });
  },
  // 点击下拉列表
  optionTap: function (e) {
    var Index = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    this.setData({
      index: Index,
      show: !this.data.show
    });
  },
  phoneInput: function (e) {
    //监听手机号输入
    this.data.phone = e.detail.value;
  },
  wordInput: function (e) {
    //监听留言输入
    this.data.word = e.detail.value;
  },
  //缺货登记(登记提交)
  queHuo: function (e) {
    var data = e.detail.value; //表单消息
    var phone = data['phone']; //用户手机号
    var quehuo_num = data['quehuo_num']; //缺货数量
    var word = data['word']; //留言
    var aid = this.data.aid;
    var priceid = this.data.priceid;
    console.log(priceid + '-----' + aid + '-----' + word + '-----' + quehuo_num + '-----' + phone);
    var telRule = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[1|3|5|8|9])[0-9]{8}$/;
    if (phone == '') {
      this.showMessage('手机号不能为空');
    } else if (!telRule.test(phone)) {
      this.showMessage('手机号格式不正确');
    } else {
      jqdetail.getquehuo(aid, phone, quehuo_num, word, priceid, res => {
        console.log(res);
        this.setData({
          stockFlag: "true"
        });
      });
      this.showMessage('提交成功');
    }
  },
  //订票须知展开收起
  noticeClick: function (e) {
    var _fold = e.target.dataset.fold;
    var _toggle = this.data.datas[_fold].toggle;
    this.data.datas[_fold].toggle = !_toggle; //设置之后我们要把数据从新添回去

    this.setData({
      datas: this.data.datas
    });
  },
  //切换订票，须知，介绍，点评
  menuClick: function (e) {
    var that = this;
    var _menu = e.target.dataset.menu;
    that.setData({
      _menu: _menu,
      _list: _menu
    });
  },
  //排序
  compare: function (property, bol) {
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];

      if (bol) {
        return value1 - value2;
      } else {
        return value2 - value1;
      }
    };
  },
  // 拨打电话
  calling: function () {
    tt.makePhoneCall({
      phoneNumber: '188-6035-1905'
    });
  },
  //分享
  onShareAppMessage: function () {
    util.sharePage();
  },
  // 获取滚动条当前位置
  onPageScroll: function (e) {
    if (e.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  //地图导航
  getmap: function (e) {
    var mpcoordinate = e.target.dataset.mpcoordinate;
    var shorttitle = e.target.dataset.shorttitle;
    var venue = e.target.dataset.venue;
    var a = mpcoordinate.split(",");
    var latitude = a[1] * 1;
    var longitude = a[0] * 1;
    var result3 = WSCoordinate.transformFromBaiduToGCJ(latitude, longitude);
    latitude = result3.latitude;
    longitude = result3.longitude;
    console.log(result3);
    console.log(latitude);
    console.log(longitude);
    tt.openLocation({
      latitude: latitude,
      longitude: longitude,
      scale: 18,
      name: shorttitle,
      address: venue
    });
  },
  //回到顶部
  goTop: function () {
    // 一键回到顶部
    util.goTop();
  },
  //关闭公告
  gg_Close: function () {
    this.setData({
      gonggao: true
    });
  },
  fxShow: function () {
    this.setData({
      fxFlag: false
    });
  },
  fxClose: function () {
    this.setData({
      fxFlag: true
    });
  },
  //返回首页 
  get_index: function () {
    tt.switchTab({
      url: '/pages/index/index'
    });
  },
  //打开关闭提示弹框
  showMessage: function (text) {
    var that = this;
    that.setData({
      showMessage: true,
      messageContent: text
    });
    setTimeout(function () {
      that.setData({
        showMessage: false,
        messageContent: ''
      });
    }, 3000);
  },
  //生成海报并保存到本地
  ewmOpen: function () {
    console.log(this.data.id); //获取二维码并显示背景图片

    var _page = "pages/jqdetail/jqdetail";
    jqdetail.get_qr_code(this.data.id, this.data.mMid, _page, res => {
      console.log(11, res);
      this.setData({
        qr_code: res,
        CodeFlag: false,
        fxFlag: true,
        maskHidden: false
      });
      tt.showToast({
        title: '海报生成中...',
        icon: 'loading',
        duration: 2000
      });
      var that = this;
      setTimeout(function () {
        that.createNewImg();
        tt.hideToast();
        that.setData({
          maskHidden: true
        });
      }, 1000);
    });
  },
  //画图
  createNewImg: function () {
    console.log('画图');
    var that = this; //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
    var path1 = "../../image/fx3.png";
    var path2 = that.data.litpic; //项目图片
    var path3 = "../../image/logo.png";
    var _Jqdetail = that.data.Jqdetail;
    var _title = _Jqdetail.shorttitle; //标题
    var _shouyeprice = _Jqdetail.shouyeprice; //价格
    var _recommend = _Jqdetail.recommend; //推荐理由
    var _venue = _Jqdetail.venue; //大概地址
    var wx_image = "../../image/dhpw.png"; // 微信头像
    var wx_name = '大河票务网'; //微信名称

    if (_title.length > 9) {
      _title = _title.substring(0, 9) + '...';
    }

    if (_venue.length > 20) {
      _venue = _venue.substring(0, 20) + '...';
    }

    if (_recommend.length > 25) {
      var _recommend2 = _recommend.substring(25, 42) + '...';

      _recommend = _recommend.substring(0, 25);
    } else {
      var _recommend2 = '';
    }

    if (!/^https/.test(path2)) {
      path2 = path2.replace(/^http/, "https");
    }

    if (_shouyeprice.length <= 2) {
      var qi = 70;
    } else if (_shouyeprice.length <= 3) {
      var qi = 90;
    } else {
      var qi = 100;
    }
    var path4 = that.data.qr_code; //二维码
    // that.base64src(path4);
    // path4 = Small_program_code2;
    console.log(path4);
    tt.downloadFile({
      url: path2,
      success: function (res) {
        path2 = res.tempFilePath;
        console.log('临时文件地址是path2：' + res.tempFilePath); //绘制图片

        tt.createSelectorQuery().select('#mycanvas').fields({
          node: true,
          size: true
        }).exec(res => {
          const canvas = res[0].node;
          const context = canvas.getContext('2d');
          that.setData({
            canvas,
            context
          });
          const dpr = tt.getSystemInfoSync().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          context.scale(dpr, dpr);
          context.fillStyle = "#fff";
          context.fillRect(0, 0, 375, 665);
          context.fillRect(15, 15, 300, 425); //矩形框

          that.canvasDraw(path2, 15, 133, 344, 206);
          that.canvasDraw(wx_image, 40, 40, 54, 54);
          that.canvasDraw(path3, 116, 49, 226, 40);
          that.canvasDraw(path4, 247, 480, 92, 92);
          context.stroke();
          context.font = 'normal 31px sans-serif';
          context.fillStyle = 'red';
          context.fillText(_title, 30, 382);
          context.font = 'normal  12px sans-serif';
          context.fillStyle = 'rgb(51,51,51)';
          context.fillText(_recommend, 30, 407);
          context.font = 'normal  12px sans-serif';
          context.fillStyle = 'rgb(51,51,51)';
          context.fillText(_recommend2, 30, 425);
          context.font = 'normal  14px sans-serif';
          context.fillStyle = 'rgb(128,128,128)';
          context.fillText(_venue, 30, 447);
          context.font = 'noraml 15px sans-serif';
          context.fillStyle = 'rgb(128,128,128)';
          context.fillText(wx_name, 35, 115);
          context.font = 'normal  33px sans-serif';
          context.fillStyle = 'rgb(255,2,0)';
          context.fillText(_shouyeprice, 30, 489);
          context.font = 'normal  22px sans-serif';
          context.fillStyle = 'rgb(128,128,128)';
          context.fillText('起', qi, 489);
          context.font = 'normal  14px sans-serif';
          context.fillStyle = '#999';
          context.textAlign = 'left';
          context.fillText("长按识别购买", 248, 600);
          context.stroke();
          context.font = 'normal 13px sans-serif';
          context.fillStyle = 'rgb(151,153,152)';
          context.textAlign = 'left';
          context.fillText("大河票务 景点门票 演出门票 本地吃喝玩乐", 69, 640);
          context.stroke();
          context.lineCap = 'butt';
          context.lineWidth = '1px';
          context.moveTo(46, 635);
          context.lineTo(55, 635);
          context.strokeStyle = 'rgb(151,153,152)';
          context.stroke();
          context.lineCap = 'butt2';
          context.lineWidth = '1px';
          context.moveTo(326, 635);
          context.lineTo(335, 635);
          context.strokeStyle = 'rgb(151,153,152)';
          context.stroke();
        }); //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时

        setTimeout(function () {
          tt.canvasToTempFilePath({
            canvas: that.data.canvas,
            success: function (res) {
              console.log(33, res);
              var tempFilePath = res.tempFilePath;
              tt.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                //这个只是测试路径，没有效果
                success: function (res) {
                  console.log("success");
                },

                fail(res) {
                  console.log(res);
                }

              });
              that.setData({
                imagePath: tempFilePath,
                canvasHidden: true
              });
            },
            fail: function (res) {
              console.log(res);
            }
          });
        }, 500);
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  // 图片
  canvasDraw(path, x, y, w, h) {
    let img = this.data.canvas.createImage();
    img.src = path;

    img.onload = () => {
      this.data.context.drawImage(img, x, y, w, h);
    };
  },

  //base64字符串转图片
  base64src: function (base64data) {
    console.log('base64');
    return new Promise((resolve, reject) => {
      const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];

      if (!format) {
        reject(new Error('ERROR_BASE64SRC_PARSE'));
      }

      var filePath = `${tt.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${this.data.id}.${format}`;
      Small_program_code2 = filePath;
      const buffer = tt.base64ToArrayBuffer(bodyData);
      fsm.writeFile({
        filePath,
        data: buffer,
        encoding: 'binary',

        success() {
          resolve(filePath);
        },

        fail() {
          reject(new Error('ERROR_BASE64SRC_WRITE'));
        }

      });
    });
  },
  //关闭蒙版，和海报
  imagePathBox: function () {
    this.setData({
      maskHidden: false
    });
  },
  remove: function (array, val) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == val) {
        array.splice(i, 1);
      }
    }
    return -1;
  },
// 判断是否登录然后跳转
  topay(e){
    const token=tt.getStorageSync('token');
    const id=e.currentTarget.dataset.id
    const url = '/pages/SubmitJqOrder/SubmitJqOrder?aid='+this.data.Jqdetail.aid+'&id='+id+'&z='+this.data.z
    if (token == ''){
      util.login(url)
    }else{
      tt.navigateTo({
        url: url // 指定页面的url
      });
    }
  }
});